﻿using System;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Localization.Models;
using Orchard.Localization.Services;
using Orchard.Projections.Descriptors.Filter;
using IFilterProvider = Orchard.Projections.Services.IFilterProvider;

namespace Vitus.Localization.Projections
{
    [OrchardFeature("Vitus.CultureProjectionFilters")]
    public class SpecificCultureFilter : IFilterProvider
    {
        private readonly ICultureManager _cultureManager;

        public SpecificCultureFilter(ICultureManager cultureManager)
        {
            _cultureManager = cultureManager;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Describe(DescribeFilterContext describe)
        {
            describe.For("Localization", T("Localization"), T("Localization"))
                .Element("SpecificCulture", T("Specific Culture"), T("Specific culture localizations"),
                         ApplyFilter,
                         DisplayFilter,
                         "SpecificCultureFilter"
                );
        }

        public void ApplyFilter(FilterContext context)
        {
            var culture = Convert.ToString(context.State.Culture);
            int cultureId = _cultureManager.GetCultureByName(culture).Id;

            context.Query = context.Query.Where(
                x => x.ContentPartRecord<LocalizationPartRecord>(),
                x => x.Eq("CultureId", cultureId));
        }

        public LocalizedString DisplayFilter(FilterContext context)
        {
            string culture = context.State.Culture;

            if (String.IsNullOrEmpty(culture))
            {
                return T("Any content item");
            }

            return T("Content localizations of the culture {0}", culture);
        }
    }


}